<!--
  子商户表单组件
  @description 子商户新增/编辑表单对话框
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.subMerchantName')" prop="subMerchantName">
            <el-input
              v-model="formData.subMerchantName"
              :placeholder="t('settle.subMerchant.rules.subMerchantNameRequired')"
              maxlength="100"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.parentMerchantNo')" prop="parentMerchantNo">
            <el-select
              v-model="formData.parentMerchantNo"
              :placeholder="t('settle.subMerchant.rules.parentMerchantNoRequired')"
              style="width: 100%"
              filterable
              remote
              :remote-method="searchMerchants"
              :loading="merchantLoading"
            >
              <el-option
                v-for="merchant in merchantOptions"
                :key="merchant.merchantNo"
                :label="`${merchant.merchantNo} - ${merchant.merchantName}`"
                :value="merchant.merchantNo"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.businessType')" prop="businessType">
            <el-select
              v-model="formData.businessType"
              :placeholder="t('settle.subMerchant.rules.businessTypeRequired')"
              style="width: 100%"
            >
              <el-option
                v-for="(label, value) in businessTypeOptions"
                :key="value"
                :label="label"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.businessLicense')" prop="businessLicense">
            <el-input
              v-model="formData.businessLicense"
              :placeholder="t('settle.subMerchant.rules.businessLicenseRequired')"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.contactName')" prop="contactName">
            <el-input
              v-model="formData.contactName"
              :placeholder="t('settle.subMerchant.rules.contactNameRequired')"
              maxlength="50"
              show-word-limit
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.contactPhone')" prop="contactPhone">
            <el-input
              v-model="formData.contactPhone"
              :placeholder="t('settle.subMerchant.rules.contactPhoneRequired')"
              maxlength="20"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.contactEmail')" prop="contactEmail">
            <el-input
              v-model="formData.contactEmail"
              :placeholder="t('settle.common.pleaseInput') + t('settle.subMerchant.contactEmail')"
              maxlength="100"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.settleAccount')" prop="settleAccount">
            <el-input
              v-model="formData.settleAccount"
              :placeholder="t('settle.subMerchant.rules.settleAccountRequired')"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.settleCycle')" prop="settleCycle">
            <el-select
              v-model="formData.settleCycle"
              :placeholder="t('settle.subMerchant.rules.settleCycleRequired')"
              style="width: 100%"
            >
              <el-option
                v-for="(label, value) in settleCycleOptions"
                :key="value"
                :label="label"
                :value="parseInt(value)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('settle.subMerchant.feeRate')" prop="feeRate">
            <el-input-number
              v-model="formData.feeRate"
              :placeholder="t('settle.subMerchant.rules.feeRateRequired')"
              :min="0"
              :max="100"
              :precision="4"
              :step="0.0001"
              style="width: 100%"
            />
            <span class="ml-5px">%</span>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item :label="t('settle.subMerchant.businessAddress')" prop="businessAddress">
        <el-input
          v-model="formData.businessAddress"
          :placeholder="t('settle.subMerchant.rules.businessAddressRequired')"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
      
      <el-form-item :label="t('settle.common.remark')" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :placeholder="t('settle.common.pleaseInput') + t('settle.common.remark')"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">
        {{ t('settle.common.confirm') }}
      </el-button>
      <el-button @click="dialogVisible = false">
        {{ t('settle.common.cancel') }}
      </el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { 
  getSubMerchantApi, 
  createSubMerchantApi, 
  updateSubMerchantApi 
} from '@/api/settle/subMerchant'
import { getMerchantListApi } from '@/api/settle/merchant'
import type { SubMerchantVO, SubMerchantCreateReqVO, SubMerchantUpdateReqVO, MerchantVO } from '@/api/settle/types'
import { BusinessTypeEnum, SettleCycleEnum } from '@/api/settle/types'
import { Dialog } from '@/components/Dialog'

defineOptions({ name: 'SubMerchantForm' })

const { t } = useI18n()

// 弹窗相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)

// 表单相关
const formRef = ref<FormInstance>()
const formType = ref('')
const formData = ref<SubMerchantCreateReqVO>({
  subMerchantName: '',
  parentMerchantNo: '',
  businessType: BusinessTypeEnum.ENTERPRISE,
  businessLicense: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  settleAccount: '',
  settleCycle: SettleCycleEnum.DAILY,
  feeRate: 0,
  businessAddress: '',
  remark: ''
})

// 商户选项
const merchantOptions = ref<MerchantVO[]>([])
const merchantLoading = ref(false)

// 选项数据
const businessTypeOptions = {
  [BusinessTypeEnum.ENTERPRISE]: t('settle.subMerchant.businessTypes.enterprise'),
  [BusinessTypeEnum.INDIVIDUAL]: t('settle.subMerchant.businessTypes.individual'),
  [BusinessTypeEnum.MICRO]: t('settle.subMerchant.businessTypes.micro')
}

const settleCycleOptions = {
  [SettleCycleEnum.DAILY]: t('settle.subMerchant.settleCycles.daily'),
  [SettleCycleEnum.WEEKLY]: t('settle.subMerchant.settleCycles.weekly'),
  [SettleCycleEnum.MONTHLY]: t('settle.subMerchant.settleCycles.monthly')
}

// 表单校验规则
const formRules = reactive<FormRules>({
  subMerchantName: [
    { required: true, message: t('settle.subMerchant.rules.subMerchantNameRequired'), trigger: 'blur' }
  ],
  parentMerchantNo: [
    { required: true, message: t('settle.subMerchant.rules.parentMerchantNoRequired'), trigger: 'change' }
  ],
  businessType: [
    { required: true, message: t('settle.subMerchant.rules.businessTypeRequired'), trigger: 'change' }
  ],
  businessLicense: [
    { required: true, message: t('settle.subMerchant.rules.businessLicenseRequired'), trigger: 'blur' }
  ],
  contactName: [
    { required: true, message: t('settle.subMerchant.rules.contactNameRequired'), trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: t('settle.subMerchant.rules.contactPhoneRequired'), trigger: 'blur' },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: t('settle.subMerchant.rules.contactPhoneFormat'), 
      trigger: 'blur' 
    }
  ],
  contactEmail: [
    { 
      type: 'email', 
      message: t('settle.subMerchant.rules.contactEmailFormat'), 
      trigger: 'blur' 
    }
  ],
  settleAccount: [
    { required: true, message: t('settle.subMerchant.rules.settleAccountRequired'), trigger: 'blur' }
  ],
  settleCycle: [
    { required: true, message: t('settle.subMerchant.rules.settleCycleRequired'), trigger: 'change' }
  ],
  feeRate: [
    { required: true, message: t('settle.subMerchant.rules.feeRateRequired'), trigger: 'blur' }
  ],
  businessAddress: [
    { required: true, message: t('settle.subMerchant.rules.businessAddressRequired'), trigger: 'blur' }
  ]
})

// 计算属性
const isUpdate = computed(() => formType.value === 'update')

// 事件定义
const emit = defineEmits(['success'])

/**
 * 打开弹窗
 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? t('settle.common.add') + t('settle.subMerchant.title') : t('settle.common.edit') + t('settle.subMerchant.title')
  formType.value = type
  resetForm()
  
  // 加载商户列表
  await loadMerchants()
  
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await getSubMerchantApi(id)
      Object.assign(formData.value, data)
    } catch (error) {
      console.error('获取子商户详情失败:', error)
    } finally {
      formLoading.value = false
    }
  }
}

/**
 * 提交表单
 */
const submitForm = async () => {
  const valid = await formRef.value?.validate()
  if (!valid) return
  
  formLoading.value = true
  try {
    const data = { ...formData.value }
    if (isUpdate.value) {
      await updateSubMerchantApi(data as SubMerchantUpdateReqVO)
      ElMessage.success(t('settle.subMerchant.tips.updateSuccess'))
    } else {
      await createSubMerchantApi(data)
      ElMessage.success(t('settle.subMerchant.tips.createSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('保存子商户失败:', error)
  } finally {
    formLoading.value = false
  }
}

/**
 * 重置表单
 */
const resetForm = () => {
  formData.value = {
    subMerchantName: '',
    parentMerchantNo: '',
    businessType: BusinessTypeEnum.ENTERPRISE,
    businessLicense: '',
    contactName: '',
    contactPhone: '',
    contactEmail: '',
    settleAccount: '',
    settleCycle: SettleCycleEnum.DAILY,
    feeRate: 0,
    businessAddress: '',
    remark: ''
  }
  formRef.value?.resetFields()
}

/**
 * 加载商户列表
 */
const loadMerchants = async () => {
  try {
    merchantLoading.value = true
    const data = await getMerchantListApi(1) // 只获取审核通过的商户
    merchantOptions.value = data
  } catch (error) {
    console.error('加载商户列表失败:', error)
  } finally {
    merchantLoading.value = false
  }
}

/**
 * 搜索商户
 */
const searchMerchants = async (query: string) => {
  if (query) {
    // 这里可以实现远程搜索逻辑
    await loadMerchants()
  }
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.ml-5px {
  margin-left: 5px;
}
</style>
